package com.heima.dao;

import com.heima.domian.Student;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class StudentDao {

    /**
     * 添加
     *
     * @param
     */
    public void addStudent(Student stu) {
        try {
            Class.forName("com.mysql.jdbc.Driver");

            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db10", "root", "itheima888");

            PreparedStatement preparedStatement = conn.prepareStatement("insert  into  t_stu  values(null,?,?,?)");

            preparedStatement.setString(1   , stu.getName());
            preparedStatement.setInt(2, stu.getAge());
            preparedStatement.setInt(3, stu.getScore());
            preparedStatement.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static List<Student> findAll() {
        try {
            List<Student> list = new ArrayList<>();
            Class.forName("com.mysql.jdbc.Driver");

            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db10", "root", "itheima888");

            PreparedStatement preparedStatement = conn.prepareStatement("select * from  t_stu");

            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                Student stu = new Student();
                stu.setId(resultSet.getInt("id"));
                stu.setName(resultSet.getString("name"));
                stu.setAge(resultSet.getInt("age"));
                stu.setScore(resultSet.getInt("score"));
                list.add(stu);
            }

            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}